package com.music.note_android.ui.folder

import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog

import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.music.note_android.R
import com.music.note_android.data.model.Folder
import androidx.recyclerview.widget.RecyclerView
import android.widget.LinearLayout
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
class FolderManagementFragment : Fragment() {

    private val viewModel: FolderManagementViewModel by viewModels()
    private lateinit var folderAdapter: FolderAdapter
    
    // UI组件
    private lateinit var toolbar: MaterialToolbar
    private lateinit var progressIndicator: LinearProgressIndicator
    private lateinit var recyclerView: RecyclerView
    private lateinit var emptyStateLayout: LinearLayout
    private lateinit var fabAddFolder: FloatingActionButton

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_folder_management, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        

        
        initViews(view)
        setupToolbar()
        setupRecyclerView()
        setupFab()
        observeViewModel()
        
        // 加载文件夹数据
        viewModel.loadFolders()
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    private fun initViews(view: View) {
        toolbar = view.findViewById(R.id.toolbar)
        progressIndicator = view.findViewById(R.id.progress_indicator)
        recyclerView = view.findViewById(R.id.recycler_view_folders)
        emptyStateLayout = view.findViewById(R.id.empty_state_layout)
        fabAddFolder = view.findViewById(R.id.fab_add_folder)
    }

    private fun setupToolbar() {
        toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
        
        // 启用选项菜单
        setHasOptionsMenu(true)
    }

    private fun setupRecyclerView() {
        folderAdapter = FolderAdapter(
            onFolderClick = { folder ->
                // 点击文件夹，导航到文件夹内笔记列表
                onViewFolderNotes(folder)
            },
            onRenameFolder = { folder ->
                showRenameFolderDialog(folder)
            },
            onDeleteFolder = { folder ->
                showDeleteFolderDialog(folder)
            },
            onMoveNotesToFolder = { folder ->
                // TODO: 实现移动笔记功能
                Toast.makeText(context, "移动笔记功能开发中", Toast.LENGTH_SHORT).show()
            },
            onViewFolderNotes = { folder ->
                onViewFolderNotes(folder)
            }
        )
        
        recyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = folderAdapter
        }
    }

    private fun setupFab() {
        fabAddFolder.setOnClickListener {
            showCreateFolderDialog()
        }
    }

    private fun observeViewModel() {
        // 观察文件夹列表
        lifecycleScope.launch {
            viewModel.folders.collect { folders ->
                folderAdapter.submitList(folders)
                updateEmptyState(folders.isEmpty())
            }
        }
        
        // 观察UI状态
        lifecycleScope.launch {
            viewModel.uiState.collect { state ->
                progressIndicator.visibility = if (state.isLoading) View.VISIBLE else View.GONE
                
                state.error?.let { error ->
                    Toast.makeText(context, error, Toast.LENGTH_LONG).show()
                }
                
                state.message?.let { message ->
                    Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun updateEmptyState(isEmpty: Boolean) {
        if (isEmpty) {
            recyclerView.visibility = View.GONE
            emptyStateLayout.visibility = View.VISIBLE
        } else {
            recyclerView.visibility = View.VISIBLE
            emptyStateLayout.visibility = View.GONE
        }
    }

    private fun showCreateFolderDialog() {
        CreateFolderDialog.newInstance { folderName ->
            viewModel.createFolder(folderName)
        }.show(childFragmentManager, "CreateFolderDialog")
    }

    private fun showRenameFolderDialog(folder: Folder) {
        RenameFolderDialog.newInstance(folder) { newName ->
            viewModel.renameFolder(folder.id, newName)
        }.show(childFragmentManager, "RenameFolderDialog")
    }

    private fun showDeleteFolderDialog(folder: Folder) {
        AlertDialog.Builder(requireContext())
            .setTitle("删除文件夹")
            .setMessage("确定要删除文件夹 \"${folder.name}\" 吗？\n\n文件夹内的笔记将移动到默认文件夹。")
            .setPositiveButton("删除") { _, _ ->
                viewModel.deleteFolder(folder.id)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun onViewFolderNotes(folder: Folder) {
        // 导航到笔记列表页面，传递文件夹ID参数
        val action = FolderManagementFragmentDirections.actionFolderToNotes(folder.id)
        findNavController().navigate(action)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.folder_management_menu, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_add_folder -> {
                showCreateFolderDialog()
                true
            }
            R.id.action_search_folder -> {
                // TODO: 实现搜索功能
                Toast.makeText(context, "搜索功能开发中", Toast.LENGTH_SHORT).show()
                true
            }
            R.id.action_sort_by_name -> {
                // TODO: 实现按名称排序
                Toast.makeText(context, "按名称排序功能开发中", Toast.LENGTH_SHORT).show()
                true
            }
            R.id.action_sort_by_time -> {
                // TODO: 实现按时间排序
                Toast.makeText(context, "按时间排序功能开发中", Toast.LENGTH_SHORT).show()
                true
            }
            R.id.action_sort_by_note_count -> {
                // TODO: 实现按笔记数量排序
                Toast.makeText(context, "按笔记数量排序功能开发中", Toast.LENGTH_SHORT).show()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }
}